import os
from datetime import datetime

from django.db import models

from api.utils.db_functions import make_short_uuid
from api.utils.enums import ProductType, FilePurpose


class Product(models.Model):
    title = models.CharField(
        help_text="商品标题", verbose_name="标题", max_length=256, null=True, blank=True
    )
    number = models.IntegerField(help_text="商品编号")
    description = models.TextField("描述", default="", blank=True, max_length=512, null=True)
    type = models.CharField("商品类型", choices=ProductType.to_choices(), max_length=256)


class ProductAttribute(models.Model):
    product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name="product_attribute")
    color = models.CharField(help_text="颜色", max_length=256)
    flavor = models.CharField(help_text="口味", max_length=256)
    memory = models.IntegerField(help_text="内存", default=8)
    block = models.IntegerField(help_text="硬盘", default=128)
    size = models.IntegerField(help_text="尺码", default=0)


def file_path(instance, file):
    file_ext = file.split(".")[-1]
    filename = "%s.%s" % (make_short_uuid(), file_ext)
    now = datetime.now()
    parent_folder = "product/%s/%s/%02d/%02d/" % (instance.media_type, now.year, now.month, now.day)

    return os.path.join(parent_folder, filename)


class ProductImages(models.Model):
    product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name="product_images")
    type = models.CharField(
        help_text="图片类型",
        choices=FilePurpose.to_choices(),
        default=FilePurpose.DESCRIPTION.value,
        max_length=256,
    )
    file = models.FileField(help_text="文件", upload_to=file_path, max_length=256)
